package com.apisix.service.controller;

import com.apisix.service.entity.Upstream;
import com.apisix.service.service.UpstreamService;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/upstreams")
public class UpstreamController {

    private final UpstreamService upstreamService;

    @Autowired
    public UpstreamController(UpstreamService upstreamService) {
        this.upstreamService = upstreamService;
    }

    @GetMapping
    public ResponseEntity<List<Upstream>> getAllUpstreams() {
        List<Upstream> upstreams = upstreamService.getAllUpstreams();
        return ResponseEntity.ok(upstreams);
    }

    @GetMapping("/{id}")
    public ResponseEntity<Upstream> getUpstreamById(@PathVariable Long id) {
        return upstreamService.getUpstreamById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @GetMapping("/upstream/{upstreamId}")
    public ResponseEntity<Upstream> getUpstreamByUpstreamId(@PathVariable String upstreamId) {
        return upstreamService.getUpstreamByUpstreamId(upstreamId)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @PostMapping
    public ResponseEntity<?> createUpstream(@RequestBody Upstream upstream) {
        try {
            // 检查upstreamId是否已存在
            if (upstream.getUpstreamId() != null && !upstream.getUpstreamId().isEmpty() && upstreamService.existsByUpstreamId(upstream.getUpstreamId())) {
                return ResponseEntity.badRequest().body(Map.of("error", "UpstreamId已存在"));
            }
            
            Upstream createdUpstream = upstreamService.createUpstream(upstream);
            return ResponseEntity.status(HttpStatus.CREATED).body(createdUpstream);
        } catch (JsonProcessingException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("error", "创建上游失败: " + e.getMessage()));
        }
    }

    @PutMapping("/{id}")
    public ResponseEntity<?> updateUpstream(@PathVariable Long id, @RequestBody Upstream upstreamDetails) {
        try {
            return upstreamService.updateUpstream(id, upstreamDetails)
                    .map(ResponseEntity::ok)
                    .orElse(ResponseEntity.notFound().build());
        } catch (JsonProcessingException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("error", "更新上游失败: " + e.getMessage()));
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteUpstream(@PathVariable Long id) {
        boolean deleted = upstreamService.deleteUpstream(id);
        if (deleted) {
            return ResponseEntity.noContent().build();
        } else {
            return ResponseEntity.notFound().build();
        }
    }
    
    @PostMapping("/sync")
    public ResponseEntity<?> syncUpstreamsFromApisix() {
        try {
            upstreamService.syncUpstreamsFromApisix();
            return ResponseEntity.ok(Map.of("message", "上游同步成功"));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("error", "同步上游失败: " + e.getMessage()));
        }
    }
} 